﻿using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace SimpleMediaManager
{
    public class DataItem
    {
        public int Key;
        public Movie Value;

        public DataItem() { }

        public DataItem(int key, Movie value)
        {
            this.Key = key;
            this.Value = value;
        }
    }

    public class Database
    {
        private Dictionary<int, Movie> movies;

        public Dictionary<int, Movie> Movies
        {
            get { return this.movies; }
        }

        public Database()
        {
            this.movies = new Dictionary<int, Movie>();
        }

        public Database(Dictionary<int, Movie> movies)
        {
            this.movies = movies;
        }

        public void Add(int key, Movie movie)
        {
            this.movies.Add(key, movie);
        }

        public void Remove(int key)
        {
            this.movies.Remove(key);
        }

        public void Serialize(string file)
        {
            List<DataItem> tempData = new List<DataItem>(movies.Count);

            foreach (int key in movies.Keys)
            {
                tempData.Add(new DataItem(key, movies[key]));
            }

            XmlSerializer serializer = new XmlSerializer(typeof(List<DataItem>));
            StreamWriter writer = File.CreateText(file);

            serializer.Serialize(writer, tempData);

            writer.Flush();
            writer.Close();
        }

        public static Database Deserialize(string file)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<DataItem>));
            StreamReader reader = File.OpenText(file);
            List<DataItem> tempData = (List<DataItem>)serializer.Deserialize(reader);

            reader.Close();

            Dictionary<int, Movie> movies = new Dictionary<int, Movie>();

            foreach (DataItem data in tempData)
            {
                movies.Add(data.Key, data.Value);
            }

            return new Database(movies);
        }
    }
}
